package com.wyh.yuhcloud.util;


import com.wyh.yuhcloud.entity.SecurityUser;
import com.wyh.yuhcloud.entity.User;
import com.wyh.yuhcloud.entity.UserLogin;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author wyh
 * @version 1.0
 * @date 2021/12/17 16:14
 */
public class SecurityUtils {
    /**
     * 获取用户ID
     **/
    public static String getUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        return getLoginUser().getUserName();
    }

    /**
     * 获取用户
     **/
    public static UserLogin getLoginUser() {
        SecurityUser loginUser = (SecurityUser) getAuthentication().getPrincipal();
        loginUser.getCurrentUserInfo().setUserPassword("");
        return loginUser.getCurrentUserInfo();
    }


    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }


}
